import store from '@/store'
import config from '@/config'
import {
	getToken
} from '@/utils/auth'
import errorCode from '@/utils/errorCode'
import {
	toast,
	showConfirm,
	tansParams
} from '@/utils/common'
import {
	ResponseCode
} from './ajax3';
import {
	ajaxInit
} from '@/utils/ajax3';
let timeout = 10000
const baseUrl = ''

var thisLog = ''
// 设备列表
export function getThis(data) {
	thisLog = data
	return ''
}
// post封装
let httpInstance;
export const request3 = function(obj, times = 0, tokentimes = 0) {
	// 加载页面 动画
	// uni.showLoading({
	// title: "加载中",
	// mask: true,
	// });
	return new Promise((resolve, reject) => {
		if (!httpInstance) {
			httpInstance = ajaxInit();
		}
		httpInstance &&
			httpInstance
			.post(obj.url, obj.data, obj.config)
			.then((response) => {
				var flag = response.data == null && response.error.length == 0 && !(response.message
					.indexOf('异常') > -1)
				if (flag) {
					response.code = ResponseCode.SUCCESS
					uni.showToast({
						title: response.message,
						icon: 'none',
						duration: 2000
					})
				}
				// alert("返回参数4====>" + JSON.stringify(response))
				if ((response && response.data) || flag) {

					if (obj.config !== null && (response.code === ResponseCode.SUCCESS || response
							.status === 200)) {
						const CONFIG = window.config.common;
						const openSecurity = CONFIG.openSecurity;
						if (openSecurity) {
							resolve(response)
						} else {
							if (localStorage.getItem("logFlag") == true || localStorage.getItem(
									"logFlag") == 'true') {
								thisLog.$r.toast().show('入参：' + JSON.stringify(obj) + '出参：' + JSON
									.stringify(response));
							}
							resolve(response.data)
						}

						uni.hideLoading();
					} else {
						if (response.data.code === ResponseCode.REFRESHTOKEN ||
							response.data.code === ResponseCode.TOKENEXPIRED ||
							response.data.code === ResponseCode.TOKENEXPIREDNEW) {
							// setLogout('');
							// alert('退出登录')
							showConfirm('登录状态已过期，您可以继续留在该页面，或者重新登录?').then(res => {
								if (res.confirm) {
									store.dispatch('LogOut').then(res => {
										uni.reLaunch({
											url: '/pages/login'
										})
									})
								}
							})
							reject('无效的会话，或者会话已过期，请重新登录。')
						} else if (response.data.code === ResponseCode.PARAMSERR) {
							// 请求参数错误
							let message = '';
							if (response.data.error && response.data.error.length > 0) {
								response.data.error.forEach((element) => {
									message += ' ' + element.defaultMessage;
								});
								// Toast.fail(message);
								toast(response.data.message);
								// obj.error && obj.error(response.data); // 参数错误也应该进失败回调
								resolve(response.message)
							} else {
								// Toast.fail(response.data.message);
								// toast(response.data.message);
								// obj.error && obj.error(response.data); // 参数错误也应该进失败回调
								toast(response.data.message);
								resolve(response.message)
							}
						} else {
							// 失败
							// obj.error && obj.error(response.data);
							toast(response.data.error);
							resolve(response.message)
						}
					}
				} else {}
				obj.complete && obj.complete(response.data);
				uni.hideLoading();
			})
			.catch((error) => {
				// 其他错误信息待规整
				// alert("返回参数5====>" + JSON.stringify(error))
				// resolve(response.message)
				if (obj.commonComplete) {
					// obj.complete && obj.complete(null);
					// resolve(response.message)
				}
				throw error;
			});
	})




};
const requestOld = config => {
	// 是否需要设置 token
	const isToken = (config.headers || {}).isToken === false
	config.header = config.header || {}
	if (getToken() && !isToken) {
		config.header['X-Authorization'] = 'Bearer ' + getToken()
	}
	// get请求映射params参数
	if (config.params) {
		let url = config.url + '?' + tansParams(config.params)
		url = url.slice(0, -1)
		config.url = url
	}
	// 加载页面 动画
	uni.showLoading({
		title: "加载中",
		mask: true,
	});
	return new Promise((resolve, reject) => {
		uni.request({
				method: config.method || 'get',
				timeout: config.timeout || timeout,
				url: config.baseUrl || baseUrl + config.url,
				data: config.data,
				header: config.header,
				dataType: 'json',
			}).then(response => {
				if (localStorage.getItem("logFlag") == true || localStorage.getItem("logFlag") ==
					'true') {
					thisLog.$r.toast().show('入参：' + JSON.stringify(config.data) + '出参：' + JSON
						.stringify(response));
				}
				let [error, res] = response
				if (error) {
					//toast('后端接口连接异常')
					reject('')
					return
				}
				const code = res.code || 200
				const msg = errorCode[code] || res.data.msg || errorCode['default']
				if (code === 401) {
					showConfirm('登录状态已过期，您可以继续留在该页面，或者重新登录?').then(res => {
						if (res.confirm) {
							store.dispatch('LogOut').then(res => {
								uni.reLaunch({
									url: '/pages/login'
								})
							})
						}
					})
					reject('无效的会话，或者会话已过期，请重新登录。')
				} else if (code === 500) {
					toast(msg)
					reject('500')
				} else if (code !== 200) {
					toast(msg)
					reject(code)
				}
				resolve(res.data)
				uni.hideLoading();
			})
			.catch(error => {
				let {
					message
				} = error
				if (message === 'Network Error') {
					message = ''
				} else if (message.includes('timeout')) {
					message = '系统接口请求超时'
				} else if (message.includes('Request failed with status code')) {
					message = '系统接口' + message.substr(message.length - 3) + '异常'
				}
				if (message != null && message != '') {
					toast(message)
				}
				reject(error)
				uni.hideLoading();
			})
	})
}

export default requestOld